#include "thread_pool.h"
#include"mysql/mysql.h"
#include"user.h"
extern ListNode * userList;
extern char server_wd[1024];

void getsCommand(task_t * task){
   //接收文件名，查找虚拟文件表看文件是否存在
   //若文件不存在，则告知客户端，文件不存在，结束此次发送
   //若文件存在，则获取文件的md5码，然后去source文件中打开文件，传输文件内容
    char md5[33] = {0};
    char cmp[33] = {0};
    char filename[200];
    strcpy(filename, task->data);
    puts(filename);
    //查表
    //遍历用户链表获取其当前目录,平且拼接文件名字
    ListNode * p = userList;
    user_info* user;
    while(p){
        if(p->val->peerfd != task->peerfd || p->val->login_status ==LOGIN_OUT){
            p = p->next;
        }else{
            user = p->val;
            break;
        }
    }
    select_file_md5from(user, filename, md5);
    CmdType x;
    if (strcmp(md5, cmp) == 0) {
        puts("x");
        //文件不存在，告知客户端文件不存在
        x = (CmdType)(-1);
        sendn(task->peerfd, &x, sizeof(x));
        printf("File does not exist.\n");
    } else {
        puts("1");
        //文件存在，根据获取的md5拼接文件路径
        x = CMD_TYPE_FILE_EXIST;
        sendn(task->peerfd, &x, sizeof(x));

        char sourcepath[200] = {0};
        strcpy(sourcepath, server_wd);
        strcat(sourcepath, "/source/");
        strcat(sourcepath, md5);

        //打开文件
        int fd = open(sourcepath, O_RDWR);
        if (fd == -1) {
            error(1, errno, "open");
        }

        //接收文件的长度
        //若文件长度大于0断点重传
        off_t lenhalf;
        recvn(task->peerfd, &lenhalf, sizeof(lenhalf));

        if (lenhalf != 0) {
            printf("断点续传\n");
        }
        printf("offset = %ld\n", lenhalf);

        //发送文件的总长度
        struct stat st;
        memset(&st, 0, sizeof(st));
        fstat(fd, &st);
        printf("filelength: %ld\n", st.st_size);//off_t
        printf("sizeof(st.st_size): %ld\n", sizeof(st.st_size));
        sendn(task->peerfd, &st.st_size, sizeof(st.st_size));

        //续传的计算
        off_t length = st.st_size - lenhalf;

        if (length >= 100 * 1024 * 1024) {
            int ret = sendfile(task->peerfd, fd, &lenhalf, length);
            printf("ret: %d, send %s over.\n", ret, filename);
        } else {//小文件采用循环发送
                //4将文件偏移到文件
            if(lseek(fd, lenhalf, SEEK_SET) == -1){
                error(1,errno,"lseek ");
            }

            while (1) {
                train_t t;
                memset(&t, 0, sizeof(t));
                int ret = read(fd, t.buff, sizeof(t.buff));
                if (ret == 0) {
                    //文件读取完了,退出循环并通知对方退出
                    t.len = 0;
                    sendn(task->peerfd, &t.len, 4);
                    break;
                }
                t.len = ret;
                t.type =(CmdType)(-1);
                ret = sendn(task->peerfd, &t, 4 + 4 + t.len);
                if (ret == -1) {
                    break;//发生错误
                }
           }//while
        }//小文件传输else
        close(fd);
        printf("send %s over\n", filename);
    }//else
}

